package controllers

import (
	"day10_17/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
)

type ShopsController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopsController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	wheres := c.GetString("wheres")
	key := "page-" + strconv.Itoa(page) + "pageSize-" + strconv.Itoa(pageSize) + "where-" + wheres
	var map1 = make(map[string]interface{})
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		sum, shops, err := models.List(wheres, page, pageSize)
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			map1["sum"] = sum
			map1["data"] = shops
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "展示成功-mysql",
				Data: map1,
			}
			c.ServeJSON()
			jsonByte, _ := json.Marshal(&map1)
			models.Rdb.Set(key, string(jsonByte), 0)
		}
	} else {
		json.Unmarshal([]byte(val), &map1)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: map1,
		}
		c.ServeJSON()
	}
}
